<!-- 官方文档 -->
<!-- https://github.com/jonmiles/bootstrap-treeview/blob/master/README.md -->
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>tree</title>
    <link rel="stylesheet" href="./bootstrap/css/bootstrap.min.css">
    <style>
        .tree {
            cursor: pointer;
            margin: 20px;
            position: relative;
        }
        
        .tree {
            width: 230px !important;
        }
        
        .dtree-theme-item-this {
            background-color: #1492ff !important;
            color: #fff !important;
        }
        
        .dtree-theme-item:hover {
            background-color: #1492ff !important;
            color: #fff !important;
        }
        
        .dtree-theme-icon {
            color: #000 !important;
        }
        
        .dataBox>ul>.dtree-nav-item {
            padding-left: 0px !important;
        }
        
        .dtree-nav-item {
            padding-left: 12px !important;
        }
    </style>
</head>

<body>
    <div class="tree">
        <div class="dataBox">
            <div id="NationalPatent"></div>
        </div>
    </div>


</body>
<!-- <script src="./jquery-3.3.1.js"></script> -->
<script src="./jquery.js"></script>
<script src="./bootstrap/js/bootstrap.min.js"></script>

<script src="./bootstrap-treeview.js"></script>
<script>
    var tree = [{
        text: "Parent1",
        nodes: [{
            text: "Child1",
            id: 11,
            nodes: [{
                text: "Grandchild1",
                id: 444,
            }, {
                text: "Grandchild2",
                id: 0000,
            }]
        }, {
            text: "Child2"
        }]
    }, {
        text: "Parent2",
        // nodes: [], //如果没有子集了，可以不用传nodes字段，又该字段说明有子集
    }, {
        text: "Parent3"
    }, {
        text: "Parent4"
    }, {
        text: "Parent5"
    }];


    //加载根节点
    function getTree() {
        var tree = null;
        $.ajax({
            type: "post",
            url: "/http://192.168.10.168:8082/org/loadExtTreeData?parentId=F364407A1AF44B5FA1B8E39C1CBB9447",
            async: false,
            dataType: 'json',
            data: {},
            beforeSend: function() {
                // layer.load();
            },
            complete: function() {
                // layer.closeAll('loading'); //关闭loading
            },
            success: function(data) {
                console.log(data);
                tree = data;
            }
        })
        return tree;
    }


    $(function() {
        //初始化treeview

        $('#NationalPatent').treeview({
            // data: getTree(),
            data: tree,
            showTags: true,
            // enableLinks: true,
            levels: 2,
            showTags: true,
            selectable: true,
            state: {
                checked: true,
                disabled: true,
                expanded: true,
                selected: true
            },
            // expandIcon: 'glyphicon glyphicon-chevron-right',//可扩展bootstrap图标
            collapseIcon: 'glyphicon glyphicon-chevron-down',
            // nodeIcon: 'glyphicon glyphicon glyphicon-th-list',
            selectedBackColor: false,
            selectedColor: 'red',
            showCheckbox: true,
            multiSelect: true,
            onNodeChecked: function(event, data) { //选中节点
                // console.log(data);
                var selectNodes = getChildNodeIdArr(data); //获取所有子节点
                console.log(selectNodes);
                if (selectNodes) { //子节点不为空，则选中所有子节点
                    $('#NationalPatent').treeview('checkNode', [selectNodes, {
                        silent: true
                    }]);
                }
                var parentNode = $("#NationalPatent").treeview("getNode", data.parentId);
                setParentNodeCheck(data);
            },
            onNodeUnchecked: function(event, data) { //取消选中节点
                // console.log(data);

                var selectNodes = getChildNodeIdArr(data); //获取所有子节点
                if (selectNodes) { //子节点不为空，则取消选中所有子节点
                    $('#NationalPatent').treeview('uncheckNode', [selectNodes, {
                        silent: true
                    }]);
                }
            }

        });
        // $('#NationalPatent').treeview('collapseAll', {
        //     silent: false //设置初始化节点关闭
        // });
        //搜索显示获得值
        // $('#NationalPatent').treeview('search', ['Child2', {
        //     ignoreCase: false, // case insensitive
        //     exactMatch: false, // like or equals
        //     revealResults: true, // reveal matching nodes
        // }]);

        // //默认选中
        // $('#NationalPatent').treeview('selectNode', [1, {
        //     silent: true
        // }]);
        //获得选中的值
        $('#NationalPatent').on('nodeSelected', function(event, data) {
            // alert(1);
            console.log(data);
            $('#NationalPatent').treeview('checkNode', [data.nodeId, {
                silent: true
            }]);
        });

        $('#NationalPatent').on('nodeUnselected', function(event, data) {
            // alert(1);
            console.log(data);
            $('#NationalPatent').treeview('uncheckNode', [data.nodeId, {
                silent: true
            }]);
        });

        //treeview节点展开事件
        $('#NationalPatent').on('nodeExpanded', function(event, data) {
            console.log(data); //data 当前行的数据
            console.log(data.id);
            var id = data['nodeId']; //获取节点的nodeid （nodeid是treeview自动生成的，每个节点不同）
            $.ajax({ //异步加载当前节点的子节点数据
                type: "post",
                url: "/GuideSeach/InitIPCTreeViewByFatherID",
                async: false,
                dataType: 'json',
                data: {
                    PIPC: data['text']
                },
                beforeSend: function() {
                    // layer.load();
                },
                complete: function() {
                    // layer.closeAll('loading'); //关闭loading
                },
                success: function(result) {
                    //再添加节点前，需要清空展开节点下的子节点，否则会累计很多节点。
                    $("#NationalPatent").treeview("deleteChildrenNode", id); //删除当前节点下的所有子节点
                    //根据返回的数据源，添加子节点
                    for (var i = 0; i < result.length; i++) {
                        //result[i]的格式如下图
                        $("#NationalPatent").treeview("addNode", [id, {
                            node: result[i],
                            silent: true
                        }]);
                    }
                }
            })
        });
    });


    function getChildNodeIdArr(node) {
        var ts = [];
        if (node.nodes) {
            for (x in node.nodes) {
                ts.push(node.nodes[x].nodeId);
                if (node.nodes[x].nodes) {
                    var getNodeDieDai = getChildNodeIdArr(node.nodes[x]);
                    for (j in getNodeDieDai) {
                        ts.push(getNodeDieDai[j]);
                    }
                }
            }
        } else {
            ts.push(node.nodeId);
        }
        return ts;
    }

    function setParentNodeCheck(node) {
        var parentNode = $("NationalPatent").treeview("getNode", node.parentId);
        if (parentNode.nodes) {
            var checkedCount = 0;
            for (x in parentNode.nodes) {
                if (parentNode.nodes[x].state.checked) {
                    checkedCount++;
                } else {
                    break;
                }
            }
            if (checkedCount === parentNode.nodes.length) {
                $("NationalPatent").treeview("checkNode", parentNode.nodeId);
                setParentNodeCheck(parentNode);
            }
        }
    }
</script>

</html>